﻿using System;
using NHibernate;
using cludg.Infrastructure.Core.Logging;

namespace nsadv.Statistic.Repository.NHibernate.Sessions
{
	public class NHibernateSessionControllerSimple : INHibernateSessionController, IDisposable
	{
		protected readonly NHibernateController Controller;
		protected readonly ILogger Logger;

		public NHibernateSessionControllerSimple(
			NHibernateController controller,
			ILogger logger = null)
		{
			Controller = controller;
			Logger = logger ?? new NullLogger();
		}

		protected ISession Session = null;

		protected void CheckSession()
		{
			if (Session == null)
			{
				Session = Controller.OpenSession();
				Session.FlushMode = FlushMode.Commit;
				Logger.Info("Open NHibernate session");
			}
		}

		public ISession Current
		{
			get
			{
				CheckSession();

				if (!Session.IsConnected)
					Session.Reconnect();

				return Session;
			}
		}

		public void Reset()
		{
			Session = null;
			Logger.Info("NHibernate session reset");
		}

		public void Dispose()
		{
			if (Session != null)
			{
				var s = Session;
				Session = null;
				s.Dispose();
			}
		}
	}
}
